package com.chouren.goandroid.ui.fragment.adapter;

import java.util.List;

import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.chouren.goandroid.R;

public class SpeakerChooseDialogAdapter extends BaseAdapter {
	private Context context;
	private List<String> speakers; // 扬声器的名字
	private StringBuilder selectedSpeaker; // 保存的扬声器路数设置
	private SparseBooleanArray checkboxItems; // 改变时的扬声器选择路数设置

	public SpeakerChooseDialogAdapter(Context context, List<String> speakers) {
		super();
		this.context = context;
		this.speakers = speakers;
		checkboxItems = new SparseBooleanArray();
	}

	public SparseBooleanArray getCheckboxItems() {
		return checkboxItems;
	}

	@Override
	public int getCount() {
		return speakers.size();
	}

	@Override
	public Object getItem(int position) {
		return speakers.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		final ViewHolder holder;

		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(
					R.layout.speaker_choose_dialog_list_item, parent, false);
			holder.mName = (TextView) convertView
					.findViewById(R.id.speaker_choose_item_name);
			holder.mSelector = (CheckBox) convertView
					.findViewById(R.id.speaker_choose_item_ck);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if (parent.getChildCount() == position) {
			if (selectedSpeaker.charAt(position) == '1') {
				holder.mSelector.setChecked(true);
			}
		}

		holder.mSelector
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						checkboxItems.put(pos, isChecked);
					}
				});

		holder.mName.setText(speakers.get(position));

		return convertView;
	}

	private static final class ViewHolder {
		TextView mName;
		CheckBox mSelector;
	}

}